import Vue from 'vue'
import { Toast } from 'vant'
import axios from 'axios'

Vue.use(Toast)

export function http ({ url, data, method, loading, errorDialog = true }) {
  return new Promise((resolve, reject) => {
    if (loading) {
      showLoading()
    }
    axios({
      url,
      data,
      method
    }).then(res => {
      if (loading) {
        hideLoading()
      }
      if (status.startsWith('4') || status.startsWith('5')) {
        showWarningToast(res.statusText)
        reject(res)
        return
      }

      resolve(res.data)
    }, err => {
      showWarningToast(err)
      reject(err)
    })
  })
}

export function showWarningToast (text) {
  Toast.fail(text)
}

export function showSuccessToast (text = '操作成功') {
  Toast.success(text)
}

export function showLoading () {
  Toast.loading({
    message: '加载中...',
    loadingType: 'spinner',
    forbidClick: true,
    duration: 0
  })
}

export function hideLoading () {
  Toast.clear()
}

function getParamsFromHref () {
  let sHref = window.location.search
  let args = sHref.split('?')
  if (args[0] == sHref) {
    return ""
  }
  let arr = args[1].split('&')
  let obj = {}
  for (let i = 0; i < arr.length; i++) {
    let arg = arr[i].split('=')
    obj[arg[0]] = arg[1]
  }
  return obj
}

export function getOpenid () {
  let params = getParamsFromHref() || {}
  let openid = params.id
  if (!openid && process.env.NODE_ENV !== 'production') {
    openid = 'oCrx85A3-nf6x8Jw47L_OgbJcP-o'
  }
  return openid
}


export function parseTime (time, cFormat) {
  if (time == null) {
    time = Date.now()
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}


export function sum (arr) {
  return arr.reduce(function (prev, curr, idx, arr) {
    return prev + curr
  })
}


let count = 0
function noop () { }

export function jsonp (url, opts, fn) {
  return new Promise((resolve, reject) => {

    if ('function' == typeof opts) {
      fn = opts
      opts = {}
    }
    if (!opts) opts = {}

    let prefix = opts.prefix || '__jp'

    // use the callback name that was passed if one was provided.
    // otherwise generate a unique name by incrementing our counter.
    let id = opts.name || (prefix + (count++))
    let isFunction = typeof opts.isFunction == 'undefined' ? true : opts.isFunction

    // let param = opts.param || 'callback';
    let param = opts.param || ''
    let timeout = null != opts.timeout ? opts.timeout : 60000
    let enc = encodeURIComponent
    let target = document.getElementsByTagName('script')[0] || document.head
    let script
    let timer

    if (timeout) {
      timer = setTimeout(() => {
        cleanup()
        // if (fn) {
        //   fn(new Error('Timeout'))
        // }
        reject()
      }, timeout)
    }

    function cleanup () {
      if (script.parentNode) {
        script.parentNode.removeChild(script)
      }

      if (isFunction) {
        window[id] = noop
      } else {
        if (Array.isArray(id)) {
          for (let i of id) {
            window[i] = undefined
          }
        } else {
          window[id] = undefined
        }

      }

      if (timer) {
        clearTimeout(timer)
      }
    }

    function cancel () {
      if (window[id]) {
        cleanup()
      }
    }

    // 真正的jsonp会触发这个函数
    if (isFunction) {
      window[id] = (data) => {
        cleanup()
        resolve(data)
      }
    }

    // add qs component
    if (param) {
      url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id)
    }

    url = url.replace('?&', '?')

    // create script
    script = document.createElement('script')
    script.src = url
    target.parentNode.insertBefore(script, target)

    script.onerror = e => {
      reject()
    }
    
    script.onload = () => {
      if (isFunction === false) {
        if (Array.isArray(id)) {
          let result = []
          for (let i of id) {
            result.push(window[i])
          }
          resolve(result)
        } else {
          resolve(window[id])
        }
        cleanup()
      }

    }
  })
}